import React, { Component } from 'react'
import { LeftCircleOutlined, LoadingOutlined, RightCircleOutlined } from '@ant-design/icons';
import {
  Table,
  Button,
  Popconfirm,
  Tooltip,
  Modal,
  Input,
  notification,
  Badge,
  Progress,
  Spin,
} from 'antd';
import NoData from '@/components/NoData';
import Router from 'umi/router';
import AddData from './components/addDataModel'
import UploadFiles from './components/uploadFiles'
import Config from './components/configModel'
import ExportFile from './components/exportFile'
import {
  getDataSetList,
  editDataSet,
  pushDataSet,
  delDataSet,
  downloadFiles,
  getFiles,
  createFile,
  getDataPurpose,
  delFiles
} from '@/services/dataCenter';
import { createAndDownloadFile } from '@/utils/utils'
import { baseUrl } from '@/utils/config.js'
import WebSocket from '@/utils/webSocket'
import { queryIndex } from "@/pages/algorithmModel/mark/components/config";

const { Search } = Input;
const { confirm } = Modal;

class DataCenter extends Component {

  constructor(argus) {
    super(argus);

    this.state = {
      dataSet: [],
      filesList: {},
      isShowAddDataModel: false,
      isShowUploadModel: false,
      isShowConfigModel: false,
      isShowExportFile: false,
      id: '',// 数据集id
      type: 0, // 任务类型
      pageNum: 1,
      pageSize: 10,
      total: null,
      keyword: '',
      isLoading: true, // 列表加载
      labelled: 0, // 前端标记 是否标注
      srcIsMark: 0,
      purposeInfos: [],
      exportId: '',//导出文件id
      exportName: '',//导出文件名称
      purposeList:[]
    };
  }
  componentDidMount() {
    localStorage.getItem("antd-pro-authority") && this.getPurposeInfo();
  }

  // 获取模型的种类用途信息和颜色
  getPurposeInfo() {
    const modelPurpose = { commonType: 'model_purpose' };
    getDataPurpose(modelPurpose).then(rs => {
      if (rs.retCode === '0') {
        const purposeInfos = [];
        rs.data.forEach(purpose => {
          purposeInfos[Number(purpose.commonValue)] =
            { name: purpose.commonName, color: purpose.commonAddition };
        });
        this.setState({ purposeInfos })
        this.queryDataSetList();
      }
    });
  }

  // 获取数据集 列表
  queryDataSetList() {
    const { pageNum, pageSize, keyword,purposeList } = this.state;
    getDataSetList({ pageNum: pageNum - 1, pageSize: pageSize, data: { dataSetName: keyword,purposeList } }).then(res => {
      if (res.retCode === '0') {
        this.setState({ dataSet: res.data.list, total: res.data.total, keyword, isLoading: false })
      }
    })
  }
  // 获取数据集下 文件列表
  onExpand(expanded, id) {
    expanded && getFiles(id).then(res => {
      if (res.retCode === '0') {
        this.setState({
          filesList: {
            ...this.state.filesList,
            [id]: res.data
          }
        })
      }
    })
  }

  // 编辑
  addData(isShowAddDataModel, id) {
    this.setState({ isShowAddDataModel, id }, () => {
      if (!isShowAddDataModel) {
        this.queryDataSetList();
        WebSocket('dataset_segment_finish', (res, rws) => {
          this.queryDataSetList();
          rws.close();
        }, close => {

        }, error => {

        });
      }
    });
  }
  // 搜索
  onSearch(keyword) {
    this.setState({ keyword, pageNum: 1 }, () => { this.queryDataSetList(); });
  }
  // 配置
  config(isShowConfigModel, id, type, labelled) { // 字段有歧义，labelled对应后端的 labelProcess
    this.setState({ isShowConfigModel, id, labelled, type: type - 0 })
    !isShowConfigModel && this.queryDataSetList();
  }
  //导出
  clickExport(isShowExportFile, exportId, exportName) {
    this.setState({ isShowExportFile, exportId, exportName })
  }
  // 删除
  delete(id) {
    const { pageNum, pageSize, total, } = this.state;
    delDataSet(id - 0).then(res => {
      if (res.retCode === '0') {
        notification['success']({
          message: '操作成功',
          key: '操作成功',
          description: '数据集删除成功',
        });
        if (pageNum > 0 && (pageNum - 1) * pageSize === total - 1) {
          this.setState({ pageNum: pageNum - 1 }, () => {
            this.queryDataSetList();
          });
        } else {
          this.queryDataSetList();
        }
      }
    })
  }
  // 上传文件
  uploadeFiles(isShowUploadModel, id, srcIsMark) {
    this.setState({ isShowUploadModel, id, srcIsMark }, () => {
      if (!isShowUploadModel) {
        this.queryDataSetList();
        this.onExpand(true, id);
        WebSocket('dataset_segment_finish', (res, rws) => {
          this.queryDataSetList();
          rws.close();
        }, close => {

        }, error => {

        });
      }
    })
  }
  // 完成并配置
  jumpConfig(type, id) {
    this.setState({ isShowAddDataModel: false, }, () => { this.config(true, id, type) })
  }
  // 翻页
  onPageChange(pageNum) {
    const { pageSize, } = this.state;
    this.setState({ pageNum }, () => { this.queryDataSetList(); });
  }
  //生成
  onCreateFile(id) {
    createFile(id).then(res => {
      if (res.retCode == '0') {
        this.queryDataSetList();
      }
    })
    WebSocket('dataset_packed', (res, rws) => {
      this.queryDataSetList();
      rws.close();
    }, close => {

    }, error => {

    });
  }

  //删除文件
  deleteFile(data) {
    delFiles(data.dataSetId, data.fileId).then(res => {
      if (res.retCode === '0') {
        notification['success']({
          message: '操作成功',
          key: '操作成功',
          description: `删除文件成功`,
        });
        this.queryDataSetList()
        this.onExpand(true, data.dataSetId);
      }
    })
  }
  // 子列表
  expandedRowRender(record, index, indent, expanded) {
    const _this = this;
    const { filesList } = _this.state;
    // 获取按钮权限列表
    const buttonList = sessionStorage.getItem('buttonList')
    //上传
    let file_upload = buttonList && buttonList.indexOf('file_upload') !== -1;
    // 下载
    let file_download = buttonList && buttonList.indexOf('file_download') !== -1;
    //删除
    let file_delete = buttonList && buttonList.indexOf('file_delete') !== -1;

    const columns = [
      { title: '文件名称', dataIndex: 'fileName', key: 'fileName' },
      { title: '上传时间', dataIndex: 'createTimeShort', key: 'createTimeShort' },
      {
        title: '文件类型', key: 'labelled', width: 100, render: (_, data) => {
          return record.labelled - 0 ? <Badge status="success" text='已标注' /> : <Badge status="default" text='未标注' />
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        render: (_, data) => (
          <>
            {file_download && <a type="link" onClick={_ => { createAndDownloadFile(`${baseUrl}/nlp/file/one?file_id=${data.fileId}`, data.fileName) }}>下载</a>}
            {/*<a type="link" onClick={this.deleteFile.bind(this,data)}>删除</a>*/}
            {file_delete && <Popconfirm title="确定删除文件？"
                                        onConfirm={this.deleteFile.bind(this, data)}>
              <a type="link">删除</a>
            </Popconfirm>}
          </>
        ),
      },
    ];

    return (
      <div style={{ padding: 8 }}>
        {file_upload && <Button type="primary" onClick={_this.uploadeFiles.bind(_this, true, record.dataSetId, record.labelled)} size={'small'} style={{ marginBottom: 8 }}>+上传文件</Button>}
        <Table columns={columns} size={'small'} dataSource={filesList[record.dataSetId]} bordered={true} rowKey={record => record.fileId} pagination={{
          simple: true, size: 'small', pageSize: 5, itemRender: (current, type, originalElement) => {
            if (type === 'prev') {
              return <LeftCircleOutlined title="上一页" />;
            }
            if (type === 'next') {
              return <RightCircleOutlined title="下一页" />;
            }
            return originalElement
          }
        }} />
      </div>
    );
  }
  filtersChange(pagination, filters){
    // console.log('filters.purpose',filters.purpose)
    this.setState({purposeList:filters.purpose && filters.purpose},_=>{
      this.queryDataSetList();
    })
  }
  render() {
    const { isShowAddDataModel, isShowUploadModel, isShowConfigModel, isShowExportFile, id, dataSet, pageNum, pageSize, total, keyword, type, isLoading,
      labelled, srcIsMark, purposeInfos, exportId, exportName } = this.state;
    // 获取按钮权限列表
    const buttonList = sessionStorage.getItem('buttonList')
    // 新增数组
    let data_add = buttonList && buttonList.indexOf('data_add') !== -1;
    // 标注
    let data_mark = buttonList && buttonList.indexOf('data_mark') !== -1;
    // 编辑
    let data_edit = buttonList && buttonList.indexOf('data_edit') !== -1;
    // 配置
    let data_config = buttonList && buttonList.indexOf('data_config') !== -1;
    // 删除
    let data_delete = buttonList && buttonList.indexOf('data_delete') !== -1;
    // 导出/生成
    let data_build_output = buttonList && buttonList.indexOf('data_build_output') !== -1;

    const columns = [
      { title: '数据集名称', dataIndex: 'dataSetName', width: 280, key: 'dataSetName' },
      { title: '简介', dataIndex: 'description', width: 360, key: 'description' },
      {
        title: '数据用途',
        dataIndex: 'purpose',
        key: 'purpose',
        width: 100,
        // eslint-disable-next-line max-len
        filters: purposeInfos.map((purpose, index) => ({ value: index, text: purpose.name })),
        // onFilter: (value, record) => (`${Number(record.purpose)}`).indexOf(value) !== -1,
        render: record => <Badge count={purposeInfos[record - 0].name} style={{ backgroundColor: `rgba(${purposeInfos[record - 0].color}, .1)`, color: `rgba(${purposeInfos[record - 0].color}, 1)`, border: `1px solid rgba(${purposeInfos[record - 0].color}, .45)`, borderRadius: 2, height: 24, lineHeight: '20px' }} />,
      },
      {
        title: '标注进度', key: 'labelProcess', width: 250, render: record => {
          if (record.segmentStatus === 1) {
            return <span style={{ color: '#29ccb1' }}><LoadingOutlined />&nbsp;&nbsp;文档切分中</span>;
          } else {
            if (record.segmentNum == 0) {
              return <span style={{ color: '#f30' }}>文档切分结果为空，请追加文档</span>
            } else {
              return <Progress size="small" percent={Number(record.labelProcess) / Number(record.segmentNum) * 100} format={percent => `${Number(record.labelProcess)} / ${Number(record.segmentNum)}`} style={{ width: '75%' }} />
            }
          }
        }
      },
      { title: '创建时间', dataIndex: 'createTimeShort', width: 160, key: 'createTimeShort', sorter: (a, b) => a.dataSetId - b.dataSetId },
      {
        title: '操作', key: 'actions', width: 200, render: record => {
          // labelStatus <Number> -1 未配置 0 未标注 1 已标注
          // dataSetStatus <Number> -1 未标注不能打包  0 已标注未打包 1 已打包可导出 2 解析打包中
          return <span>
                        {
                          ((data_mark && record.segmentNum && record.labelStatus !== -1) || (data_mark && record.segmentNum && record.purpose ===7)) ? <a type="link" onClick={_ => { Router.push(`/algorithm/mark/${record.purpose + ''}/${record.dataSetId + ''}`) }}>标注</a> : null
                        }
            {data_edit && <a type="link" onClick={this.addData.bind(this, true, record.dataSetId)}>编辑</a>}
            {data_config && record.segmentStatus !== 1 && record.purpose !==7 && < a type="link" onClick={this.config.bind(this, true, record.dataSetId, record.purpose, record.labelProcess)}>配置</a>}
            {data_delete && < Popconfirm
              title="确定删除?"
              okText="确定"
              cancelText="取消"
              onConfirm={this.delete.bind(this, record.dataSetId)}
            >
              <a type="link">删除</a>
            </Popconfirm >}
            {/*{data_build_output && record.dataSetStatus === 1 && <a type="link" onClick={_ => { createAndDownloadFile(`${baseUrl}/nlp/datacenter/dataset/files?data_set_id=${record.dataSetId}`, record.dataSetName) }}>导出</a>}*/}
            {data_build_output && record.dataSetStatus === 1 && <a type="link" onClick={this.clickExport.bind(this, true, record.dataSetId, record.dataSetName)}>导出</a>}
            {data_build_output && record.segmentNum != 0 && record.dataSetStatus === 0 && <a type="link" onClick={this.onCreateFile.bind(this, record.dataSetId)}>生成</a>}
                    </span >
        }
      },
    ];


    return (
      <>
        {isLoading ? <div className="Spin"><Spin tip="数据加载中..." /></div> :
          <>
            {
              (keyword || dataSet.length) ?
                <div style={{ padding: '8px 24px 24px' }}>
                  <div style={{ marginBottom: 16 }}>
                    {data_add && <Button type="primary" onClick={this.addData.bind(this, true, '')} style={{ marginRight: 12 }} >+新增数据</Button>}
                    <Search placeholder="数据集名称" onSearch={value => this.onSearch(value)} style={{ width: 200 }} />
                  </div>
                  <Table
                    bordered={false}
                    size={'middle'}
                    columns={columns}
                    onChange={this.filtersChange.bind(this)}
                    dataSource={dataSet}
                    className="components-table-demo-nested"
                    expandedRowRender={this.expandedRowRender.bind(this)}
                    onExpand={(expanded, record) => { this.onExpand(expanded, record.dataSetId) }}
                    rowKey={record => record.dataSetId}
                    pagination={{ total, current: pageNum, onChange: this.onPageChange.bind(this) }}
                  />
                </div>
                : <NoData title={'您还没有创建数据集'} dec={'上传标注文档并设置标签，进行标注'} btn={'数据集'} callBack={this.addData.bind(this, true, '')} />
            }
          </>
        }
        {isShowAddDataModel && <AddData id={id} isShowAddDataModel={isShowAddDataModel} callBack={this.addData.bind(this, false, id)} jumpConfig={this.jumpConfig.bind(this)} />}
        {isShowUploadModel && <UploadFiles id={id} srcIsMark={srcIsMark} isShowUploadModel={isShowUploadModel} callBack={this.uploadeFiles.bind(this, false, id)} />}
        {isShowConfigModel && <Config id={id} type={type} labelled={labelled} isShowConfigModel={isShowConfigModel} callBack={this.config.bind(this, false, id)} />}
        {isShowExportFile && <ExportFile exportId={exportId} exportName={exportName} labelled={labelled} isShowExportFile={isShowExportFile} callBack={this.clickExport.bind(this, false)} />}
      </>
    );
  }
}

export default DataCenter
